package com.example.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.demo.entity.PageUtil;
import com.example.demo.entity.User;
import com.example.demo.service.Demo5Service;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * @author 港某
 * @date 2021/9/14 10:58
 */
@CrossOrigin
@RestController
@RequestMapping(value = "demo5")
public class DemoController {

    @Resource
    Demo5Service demo5Service;

    @RequestMapping(value = "getUsers", method = {RequestMethod.GET})
    PageUtil<User> getUsers(int limit, int page) {
        return demo5Service.getUsers(limit, page);
    }

    @RequestMapping(value = "addUser", method = {RequestMethod.POST})
    void addUser(@Validated @RequestBody User user) {
        user.setId(UUID.randomUUID().toString());
        demo5Service.addUser(user);
    }

    @RequestMapping(value = "export", method = {RequestMethod.GET})
    void export(String[] ids, HttpServletResponse response) {
        List<User> users = demo5Service.getUsers(ids);
        //根据模板填充
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("导出.xls", "UTF-8"));
            File file = ResourceUtils.getFile("classpath:test.xlsx");
            EasyExcel.write(response.getOutputStream())
                    .autoCloseStream(true)
                    .withTemplate(file)
                    .sheet()
                    .doFill(users);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
